package com.cloud.common.utils;

import com.cloud.common.exception.CloudException;
import com.cloud.common.exception.enums.ErrorEnum;
import org.apache.commons.lang3.StringUtils;

import javax.servlet.http.HttpServletRequest;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * UserAgrent处理工具
 *
 * @author wangjian
 * @version 1.0.0
 * @create 2020年11月09日 19:19
 * @since JDK 1.8
 * Life is so short,do something to make yourself happy,such as coding
 */
public class UserAgrentUtil {

    private static String pattern = "^Mozilla/\\d\\.\\d\\s+\\(+.+?\\)";
    private static String pattern2 = "\\(+.+?\\)";
    private static Pattern r = Pattern.compile(pattern);
    private static Pattern r2 = Pattern.compile(pattern2);

    public static String getDeviceInfo(HttpServletRequest request) {
        String userAgent = request.getHeader("User-Agent");
        if(StringUtils.isEmpty(userAgent)){
            throw new CloudException(ErrorEnum.UNKNOWN, "User-Agent is not Empty");
        }
        return getDeviceInfo(userAgent);
    }

    private static String getDeviceInfo(String userAgent) {
        Matcher m = r.matcher(userAgent);
        String result = null;
        if (m.find()) {
            result = m.group(0);
        }
        if(StringUtils.isEmpty(result)){
            throw new CloudException(ErrorEnum.UNKNOWN, "User-Agent Incorrect format");
        }

        Matcher m2 = r2.matcher(result);
        if (m2.find()) {
            result = m2.group(0);
        }
        result = result.replace("(", "");
        result = result.replace(")", "");
        return filterDeviceInfo(result);
    }

    public static String filterDeviceInfo(String result) {
        if (StringUtils.isBlank(result)) {
            return null;
        }
        result = result.replace(" U;", "");
        result = result.replace(" zh-cn;", "");
        return result;
    }


}
